/**
 * Title: ArticleActivity.java
 * Description:
 * author: kotomifi
 * date: Jul 10, 2014
 * ©2014 apping 社区
 */
package com.apping.demo.bbs;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.sina.weibo.sdk.demo.R;
import com.apping.demo.bbs.bean.Comment;
import com.apping.demo.bbs.bean.NewsInfo;
import com.apping.demo.bbs.bean.NewsList;
import com.apping.demo.bbs.bean.NewsItem;
import com.apping.demo.bbs.bean.PostNews;
import com.apping.demo.bbs.bean.TopNewsJson;
import com.apping.demo.bbs.utils.DBUtil;
import com.apping.demo.bbs.utils.HttpTools;
import com.apping.demo.bbs.utils.HttpUtil;
import com.apping.demo.bbs.utils.NetCheck;
import com.apping.demo.bbs.utils.SharedPreferencesUtil;
import com.apping.demo.bbs.utils.SignatureUtil;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.widget.ListView;

public class ArticleActivity extends Activity {
	
	private static final int INIT_DATA_FINISH = 0;
	private static final int LOAD_DATA_FINISH = 1;
	
	private Intent intent;
	private static final String TAG = "ArticleActivity";
	private ListView articleList;
	private boolean isLastRow = false;
	
	private SQLiteDatabase db;
	
	MyBaseAdapter adapter;
	
	ArrayList<HashMap<String, Object>>listItem;
	NewsList newsList = null;
	List<NewsItem> mList = new ArrayList<NewsItem>(); // 新闻列表

	String newStr = "";
	String jsonStr;
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what) {
			case INIT_DATA_FINISH:
				
				initUI();
				break;
			case LOAD_DATA_FINISH:
				if (adapter != null) {
					adapter.notifyDataSetChanged();
				}
				break;
			}
		}
	};
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.article_list);
		db = SQLiteDatabase.openOrCreateDatabase(
				Environment.getExternalStorageDirectory().toString() + "/news.db", null);
		getNews();
		setOverflowShowingAlways();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_activity_actions, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_plus:
			return true;
		case R.id.about:
			intent = new Intent();
			intent.setClass(ArticleActivity.this, About.class);
			startActivity(intent);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public boolean onMenuOpened(int featureId, Menu menu) {
		if (featureId == Window.FEATURE_ACTION_BAR && menu != null) {
			if (menu.getClass().getSimpleName().equals("MenuBuilder")) {
				try {
					Method m = menu.getClass().getDeclaredMethod(
							"setOptionalIconsVisible", Boolean.TYPE);
					m.setAccessible(true);
					m.invoke(menu, true);
				} catch (Exception e) {
				}
			}
		}
		return super.onMenuOpened(featureId, menu);
	}
	
	/**
	 * 让不同设备都可以显示Overflow 菜单
	 */
	private void setOverflowShowingAlways() {
		try {
			ViewConfiguration config = ViewConfiguration.get(this);
			Field menuKeyField = ViewConfiguration.class
					.getDeclaredField("sHasPermanentMenuKey");
			menuKeyField.setAccessible(true);
			menuKeyField.setBoolean(config, false);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 初始化首页列表
	 * 添加新闻信息
	 */
	public void initUI() {
		
		articleList = (ListView)findViewById(R.id.articleList);
		articleList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long id) {
				intent  = new Intent(getApplication(), NewsItemPage.class);
				Bundle bundle = new Bundle();
				bundle.putLong("newsId", mList.get(position).getId());
				intent.putExtras(bundle);
				startActivity(intent);
			}
			
		});
		adapter = new MyBaseAdapter(this);
		articleList.setAdapter(adapter);
		articleList.setOnScrollListener(new MyOnScrollListener());
	}
	
	/**
	 * 检查是否连接到网络
	 * 联网获取最新新闻信息，更新新闻页面
	 * 无网络从数据库获取历史记录
	 */
	private void getNews() {
		// 检查是否连接到网络
		if (NetCheck.isNetworkConnected(this)) {
			new Thread() {
				@Override
				public void run() {
					SharedPreferencesUtil preference = new SharedPreferencesUtil(ArticleActivity.this);
					int index = 0;
					int count = 20;
					long uid = preference.readLong("com_apping_demo_bbs", "uid");
//					String ticket = preference.readString("com_apping_demo_bbs", "ticket");
//					String signature = SignatureUtil.getSignature(
//							String.valueOf(index),
//							String.valueOf(count), 
//							String.valueOf(uid), 
//							ticket);
//					String url = "http://42.96.192.37:8080/apping/demo/topnews?"
//							+ "index=" + index
//							+ "&&count=" + count
//							+ "&&uid=" + uid
//							+ "&&signature=" + signature;
					// 以下URL为测试URL
					// 实际情况请使用上面的URL
					String ticket = "bd637611abfe504f1ad40547af91687f";
					String signature2 = SignatureUtil.getSignature(
							"0",
							"20", 
							"1", 
							ticket);
					String url = "http://42.96.192.37:8080/apping/demo/topnews?"
							+ "index=0"
							+ "&&count=20"
							+ "&&uid=1"
							+ "&&signature=" + signature2;
					
					HttpTools httpTool = new HttpTools();
					try {
						httpTool.get(url);
					} catch (Exception e) {
						e.printStackTrace();
					}
					jsonStr = httpTool.getContent();
					
					// 判断是否成功获取
					String rst = JSON.parseObject(jsonStr).getString("rst");
					if (rst.equals("SUCCESS")) {
						// 清空数据库之前记录
				        DBUtil mDb = new DBUtil(db);
				        try {
				        	mDb.clearNewsList();
					        mDb.clearNewsComment();
					        mDb.clearNewsInfo();
				        } catch (Exception ex) {
				        	mDb.createTable();
				        	ex.printStackTrace();
				        }
				        
				        
						TopNewsJson newsJson = JSON.parseObject(jsonStr, TopNewsJson.class);
						// 保存当前最后索引到SharedPreference
						preference.writeInt(
								"com_apping_demo_bbs", 
								"top_news_position", 
								newsJson.getMsg().getCount());
						mList = newsJson.getMsg().getNews();
				        for (int i = 0; i < mList.size(); i++) {
				            // 添加列表到数据库
				            mDb.insert(mList.get(i));
				        }
				        // 发送消息通知UI线程更新UI组建
						handler.sendEmptyMessage(INIT_DATA_FINISH);
					} else {
						Toast.makeText(ArticleActivity.this, 
								"获取网络资源失败，请重新登陆", 2000).show();
					}
				}
			}.start();
		} else {
			// 给出提示
			// 从本地数据库加载历史信息
			DBUtil newsDb = new DBUtil(db);
			newsDb.getNewsList(mList);
			handler.sendEmptyMessage(INIT_DATA_FINISH);
			Toast.makeText(ArticleActivity.this, 
					"当前网络处于不可用状态", 2000).show();
		}
	}

	private class ViewHolder {
		public TextView title;
		public TextView likeCount;
		public ImageView likePic;
	}
	
	public class MyBaseAdapter extends BaseAdapter {
		private LayoutInflater mInflater = null;
		
		private MyBaseAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}
		
		@Override
		public int getCount() {
			return mList.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.article_item, null);
                holder = new ViewHolder();
                holder.title = (TextView)convertView.findViewById(R.id.title);
                holder.likeCount = (TextView)convertView.findViewById(R.id.likeCount);
                holder.likePic = (ImageView)convertView.findViewById(R.id.likePic);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder)convertView.getTag();
            }
            holder.title.setText(mList.get(position).getTitle());
            holder.likeCount.setText(String.valueOf(mList.get(position).getStar()));
            holder.likePic.setImageResource(R.drawable.like_32);
            return convertView;
        }
	}
	
	private class MyOnScrollListener implements OnScrollListener {

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
			if (firstVisibleItem + visibleItemCount >= totalItemCount) {
				// 发送请求处理
				isLastRow = true;
			}
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			if (isLastRow && scrollState == OnScrollListener.SCROLL_STATE_FLING) {
				loadMoreData();
			}
		}
		
		/**
		 * 下拉加载20条新闻
		 * 期间若有提交，会有重复
		 */
		public void loadMoreData() {
			new Thread() {
				@Override
				public void run() {
					SharedPreferencesUtil preference = new SharedPreferencesUtil(ArticleActivity.this);
					int index = preference.readInt("com_apping_demo_bbs", "top_news_position");
					int count = index + 20;
					
					String ticket = "bd637611abfe504f1ad40547af91687f";
					String signature = SignatureUtil.getSignature(
							String.valueOf(index),
							String.valueOf(count), 
							"1", 
							ticket);
					String url = "http://42.96.192.37:8080/apping/demo/topnews?"
							+ "index=" + index
							+ "&&count=" + count
							+ "&&uid=1"
							+ "&&signature=" + signature;
					HttpTools httpTool = new HttpTools();
					try {
						httpTool.get(url);
					} catch (Exception e) {
						e.printStackTrace();
					}
					jsonStr = httpTool.getContent();
					// 判断是否成功获取
					String rst = JSON.parseObject(jsonStr).getString("rst");
					if (rst.equals("SUCCESS")) {
						TopNewsJson newsJson = JSON.parseObject(jsonStr, TopNewsJson.class);
						// 保存当前最后索引到SharedPreference
						preference.writeInt(
								"com_apping_demo_bbs", 
								"top_news_position", 
								newsJson.getMsg().getCount() + index);

						List<NewsItem> tempList = new ArrayList<NewsItem>();
						tempList = newsJson.getMsg().getNews();
						for (int i = 0; i < tempList.size(); i++) {
							mList.add(tempList.get(i));
						}
						for (int i = 0; i < mList.size(); i++) {
				            // 添加列表到数据库
							DBUtil mDb = new DBUtil(db);
				            mDb.insert(mList.get(i));
				        }
						handler.sendEmptyMessage(LOAD_DATA_FINISH);
					} else {
						
					}
				}
			}.start();
		}
	}	
}
